<template>
  <BasicModal title="订单管理" @register="registerModal" destroyOnClose
              :showCancelBtn="false" :showOkBtn="false" :canFullscreen="false" :centered="true" :maskClosable="false" :scrollbar="{native: false}"
              :width="'95%'" :loading="loading" wrapClassName="business-order" 
              :bodyStyle="{height:'calc(100vh - 100px)', overflow:'hidden'}"
  >
    <div style="zoom: 1; min-width:1200px; padding: 0 10px 10px; margin-top: 10px; " :style="{height:'calc(100vh - 150px)', overflowY:'auto'}">
      <div class="orderInfo">
        <div class="theadSticky">
          <span class="float-left h-30px leading-30px w-25 font-bold text-lg">
            <label v-if="schedule.id">产品信息</label>
            <label v-else>订单线路</label>
          </span>
          <span class="float-left h-30px ml-20px w200 leading-30px text-base" v-if="schedule.id">
            <label class="text-sm">成人：</label>
            <label class="mr-5 text-red-500 font-bold">{{ schedule.price }}</label>
            <label class="text-sm">儿童：</label>
            <label class="mr-5 text-red-500 font-bold">{{ schedule.priceChild }}</label>
            <label class="text-sm">返佣：</label>
            <label class="mr-5 text-green-500 font-bold">{{ schedule.priceVip }}</label>
            <label class="text-sm">会员：</label>
            <label class="mr-5 text-green-500 font-bold">{{ schedule.priceRoom }}</label>
            <label class="text-sm">余位：</label>
            <label class="mr-5 text-blue-500 font-bold">{{ scheduleInfo }}</label>
          </span>
          <span class="float-right h-30px leading-30px" v-show="buttonAll">
            <a-button size="small" type="default" color="success" @click="handleBusinessDdzt('1')" :disabled="businessOption.dooButton" class="mr-2">确认订单</a-button>
            <a-button size="small" type="default" color="error" @click="handleBusinessDdzt('0')" :disabled="businessOption.canButton" class="mr-2" >取消订单</a-button>
            <a-button size="small" type="default" @click="handleBusinessUpdate" :disabled="businessOption.modButton" class="mr-2" >修改订单</a-button>
            <a-button size="small" type="default" color="warning" @click="handleBusinessPrint" class="pub_but">打印订单</a-button>
          </span>
          <span class="float-right w500 alert-tip" style="display: none"></span>
        </div>
        <table class="orderTable orderTableAlign" id="orderTable" >
          <tbody>
          <tr>
            <th>订单号</th>
            <td><div id="_orderId">{{business.orderId}}</div></td>
            <th>业务类型</th>
            <td><a-form-item class="w-120px"><JDictSelectTag dictCode="ywlxType" v-model:value="business.ywlx" :show-choose-option="false"></JDictSelectTag></a-form-item></td>
            <th>部门</th>
            <td><a-form-item class="w-130px"><JDictSelectTag dictCode="ddlxType@ddlxUser" v-model:value="business.ddlx" :show-choose-option="false" style="width: 130px"></JDictSelectTag></a-form-item></td>
            <th>成人</th>
            <td><div id="_sumAdultNo">{{business.adultNo}}</div></td>
            <th>应收</th>
            <td><div id="_ygs" class="font-500 text-right">{{business.ygs}}</div></td>
            <th>应付</th>
            <td><div id="_ygf" class="font-500 text-right">{{business.ygf}}</div></td>
          </tr>
          <tr>
            <th>订单名称</th>
            <td colspan="3" class="py-1px"><a-input type="text" v-model:value="business.travelLine" :disabled="businessOption.travelLineDisabled" class="formText" style="width:98%;"/></td>
            <th>出团日期</th>
            <td><a-date-picker v-model:value="business.cfsj" valueFormat="YYYY-MM-DD" placeholder="" style="width: 130px" :disabled="businessOption.cfsjDisabled"/></td>
            <th>儿童</th>
            <td><div id="_sumChildNo">{{business.childNo}}</div></td>
            <th>已收</th>
            <td><div id="_yjs" class="text-red-500 text-right">{{business.yjs}}</div></td>
            <th>已付</th>
            <td><div id="_yjf" class="text-green-500 text-right">{{business.yjf}}</div></td>
          </tr>
          <tr class="h-45px">
            <th class="w-80px">订单状态</th>
            <td class="w-180px"><div id="_ddztZw" :class="business.ddzt==1?'text-red-500':'text-green-500'">{{business.ddzt_zw}}</div></td>
            <th class="w-80px">操作人</th>
            <td class="w-180px"><a-form-item class="w-180px"><JDictSelectTag dictCode="sys_user,realname,id@authUser" v-model:value="business.userId" :show-choose-option="false"></JDictSelectTag></a-form-item></td>
            <th class="w-80px">录单日期</th>
            <td class="w-150px"><div id="_lrsj">{{business.lrsj}}</div></td>
            <th class="w-80px">陪同</th>
            <td class="w-100px"><div id="_sumEscortNo">{{business.escortNo}}</div></td>
            <th class="w-80px">未收</th>
            <td class="w-100px"><div id="_wsk" class="font-500 text-red-500 text-right">{{business.wsk}}</div></td>
            <th class="w-80px">利润</th>
            <td class="w-100px"><div id="_lr" class="font-500 text-blue-500 text-right">{{business.lr}}</div></td>
          </tr>
          <tr class="h-45px">
            <th class="w-80px">操作说明</th>
            <td class="tdLeft" colspan="11">
              <a-textarea v-model:value="business.bz" :rows="4" id="business_bz" class="textarea" ></a-textarea>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <div class="listtab1" id="con_menu_1" style="display: block;">
        <form id="bucForm" action="" method="post">
          <div class="theadSticky">
            <span class="float-left h-30px leading-30px w-25 font-bold text-lg">
              <label>订购单位</label>
            </span>
            <span class="float-right h-30px leading-30px" v-show="buttonAll">
              <a href="#" @click.prevent="handleCustomerAdd" :class="{'disableCss' : businessCustomerOption.btnLxrDisabled}" class="float-right font-600">添加客户</a>
              <!--a href="#" @click.prevent="handleBusinessCustomerCan" :class="{'disableCss' : businessCustomerOption.btnCanDisabled}" class="float-right mr-20px font-600" hidefocus>取消</a>
              <a href="#" @click.prevent="handleBusinessCustomerVer" :class="{'disableCss' : businessCustomerOption.btnVerDisabled}" class="float-right mr-10px font-600" hidefocus>审核</a-->
              <a href="#" @click.prevent="handleBusinessCustomerDel" :class="{'disableCss' : businessCustomerOption.btnDelDisabled}" class="float-right mr-20px font-600" hidefocus>删除</a>
              <a href="#" @click.prevent="handleBusinessCustomerAdd" :class="{'disableCss' : businessCustomerOption.btnEdtDisabled}" class="float-right mr-10px font-600" hidefocus>编辑</a>
              <a href="#" @click.prevent="handleBusinessCustomerAdd" :class="{'disableCss' : businessCustomerOption.btnAddDisabled}" class="float-right mr-10px font-600" hidefocus>添加</a>
            </span>
          </div>
          <table class="orderTable" id="buctable">
            <tbody>
            <tr class="listBg">
              <th width="20" class="check"><input type="checkbox" @change="bucAllCheck" :checked="businessCustomerOption.checked" :disabled="businessCustomerOption.disabled"/></th>
              <th width="300">订购单位</th>
              <th width="50" class="tac">人数</th>
              <th width="50" class="text-right">成人价</th>
              <th width="50" class="text-right">儿童价</th>
              <th width="80" class="text-right">应收</th>
              <th width="80" class="text-right">已收</th>
              <th width="80" class="text-right">未收</th>
              <th width="80" class="text-right">单位利润</th>
              <th class="tal">备注</th>
              <th width="90" class="tac">收客时间</th>
              <th width="90" class="tac">收客人</th>
            </tr>
            </tbody>
            <tbody v-for="(list, index) in customer.optionList" :key="index">
            <tr :class="(index%2==0) ? 'listBg' : 'cor'">
              <td><input type="checkbox" name="ids" :id="'buc'+list.id" @change="bucOneCheck(index)" :checked="businessCustomerOption.nid.indexOf(list.id) > -1" :disabled="businessCustomerOption.disabled"/></td>
              <!--td :class="bccStatClass(list.status)">{{list.statusZw}}</td-->
              <td class="text-left">
                <span class="serial-number1">{{list.rowIndex}}) </span>
                <span class="serial-dwmc">{{list.customerDwmc}}</span>
              </td>
              <td>{{list.adultNo}}'{{list.childNo}}'{{list.escortNo}}</td>
              <td class="text-right">{{list.crj}}</td>
              <td class="text-right">{{list.etj}}</td>
              <td class="text-right text-red-500">{{list.ygs}}</td>
              <td class="text-right text-green-500">{{list.yjs}}</td>
              <td class="text-right">{{list.wsk}}</td>
              <td class="text-right text-blue-500">{{list.dwlr}}</td>
              <td class="text-left">{{list.cbcbz}}</td>
              <td>{{list.sksj||list.lrsj}}</td>
              <td>{{list.skr}}</td>
            </tr><!-- @click="showTRclick(isshow)"   -->
            </tbody>
            <tfoot>
            <tr>
              <td class="tips">&nbsp;</td>
              <td class="tips">小计</td>
              <td class="tips" id="reshu">{{customer.sumAdultNo}}'{{customer.sumChildNo}}'{{customer.sumEscortNo}}</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td class="tips text-red-500 font-500 text-right" id="hjygs">{{customer.hjygs}}</td>
              <td class="tips text-green-500 font-500 text-right" id="hjyjs">{{customer.hjyjs}}</td>
              <td class="tips font-500 text-right" id="hjwsk">{{customer.hjwsk}}</td>
              <td class="tips text-blue-500 font-500 text-right" id="hjlr">{{customer.hjlr}}</td>
              <td class="tips text-left" id="dwlrbz"></td>
              <td>&nbsp;</td>
              <td class="tips">&nbsp;</td>
            </tr>
            </tfoot>
          </table>
        </form>
      </div>

      <div class="listtab1" id="con_menu_2" style="display: block;">
        <div class="theadSticky">
          <span class="float-left h-30px leading-30px w200 font-bold text-lg">
            <span>收付项目</span>
            <span v-show="buttonAll">
              <a-input-search
                v-model:value="accountOption.queryParams"
                size="small"
                placeholder="查询收付名称"
                style="width: 300px; margin-top: 3px; margin-left: 10px;"
                enter-button
                @search="onAccountSearch"
              />
            </span>
          </span>
          <span class="float-right h-30px leading-30px" v-show="buttonAll">
            <a href="#" @click.prevent="handleAccountRecall" :class="{'disableCss': accountOption.btnRecDisabled}" class="float-right font-600" hidefocus>招回</a>
            <a href="#" @click.prevent="handleAccountDel" :class="{'disableCss': accountOption.btnDelDisabled}" class="float-right mr-10px font-600" hidefocus>删除</a>
            <a href="#" @click.prevent="handleAccountStat" :class="{'disableCss': accountOption.btnStaDisabled}" class="float-right mr-10px font-600" hidefocus>提交</a>
            <a href="#" @click.prevent="handleAccountAdd" :class="{'disableCss': accountOption.btnEdtDisabled}" class="float-right mr-10px font-600" hidefocus>编辑</a>
            <a href="#" @click.prevent="handleAccountAdd" :class="{'disableCss': accountOption.btnAddDisabled}" class="float-right mr-10px font-600">添加</a>
            <a href="#" @click.prevent="handleAccountExcel" :class="{'disableCss': accountOption.btnAddDisabled}" class="float-right mr-10px font-600">导入</a>
          </span>
        </div>
        <table class="orderTable" id="acctable">
          <tbody>
          <tr class="listBg">
            <th width="20" class="check"><input type="checkbox" class="accAllCheck" @change="accAllCheck" :checked="accountOption.checked" :disabled="accountOption.disabled"/></th>
            <th width="52" class="tac">状态</th>
            <th width="52" class="tac">类型</th>
            <th width="52" class="tac">方式</th>
            <th width="260">收付名称</th>
            <th width="80" class="text-right">收入</th>
            <th width="80" class="text-right">支出</th>
            <th width="60" class="tac">部门</th>
            <th width="135" class="text-left">收支银行</th>
            <!--th width="135" v-if="accountOption.showBankdjm == true" @click="accountOption.showBankdjm = false" class="text-red-800">收支银行</th>
            <th width="135" v-if="accountOption.showBankdjm == false" @click="accountOption.showBankdjm = true" class="text-red-800">收支账户</th-->
            <th width="90" class="tac">收付时间</th>
            <th width="65" class="tac">操作人</th>
            <th>备注</th>
            <th width="90" class="tac">审核时间</th>
            <th width="70" class="tac">审核人</th>
          </tr>
          </tbody>
          <tbody v-for="(list,index) in account.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', oAccountId == list.id ? 'selected': '']" @dblclick.prevent="handleAccountEdit(list.id, list.stat, list.statZw)">
            <td><input type="checkbox" name="ids" :id="'acc' + list.id" @change="accOneCheck(index)" :checked="accountOption.nid.indexOf(list.id) > -1" :disabled="accountOption.disabled || list.stat === '2' || list.stat === '3'"/></td>
            <td :class="accStatClass(list.stat)">{{list.statZw}}</td>
            <td :class="list.sflx=='1'?'text-red-500':'text-green-500'">{{list.sflxZw}}</td>
            <td :class="accSffsClass(list.sffs)">{{list.sffsZw}}</td>
            <td class="text-left" :class="list.invoiceStat=='1'?'text-blue-500':''">
              <span class="serial-number1" v-if="list.rowIndex">{{list.rowIndex}}) </span>
              <span>{{list.sfmc}}</span>
            </td>
            <td class="text-right text-red-500">{{list.skje}}</td>
            <td class="text-right text-green-500">{{list.fkje}}</td>
            <td class="text-center">{{list.ddlxZw}}</td>
            <td class="text-left">
              <span>{{list.bankdjm}}</span>
              <span class="bg-red-500 text-white rounded-full w-20px h-15px " style="font-size: 11px;" v-if="list.xnsz == 1">虚</span>
            </td>
            <td>{{list.sfsj}}</td>
            <td>{{list.lrr}}</td>
            <td class="text-left">{{list.bz}}</td>
            <td>{{list.shsj}}</td>
            <td class="relative">{{list.shrName}}</td>
          </tr><!--  -->
          </tbody>
          <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips text-left font-500 text-blue-500"><span v-if="account.sumtotal<=100">共 {{ account.sumtotal }} 条数据</span></td>
            <td class="tips text-right font-500 text-red-500">{{account.sumskje}}</td>
            <td class="tips text-right font-500 text-green-500">{{account.sumfkje}}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          </tfoot>
        </table>
        <Pagination v-if="account.sumtotal > 100"
          style="float: right"
          v-model:current="accountOption.pageNo"
          v-model:pageSize="accountOption.pageSize"
          :total="account.sumtotal"
          :show-total="total => `共 ${account.sumtotal} 条`"
          @change="onAccountPageNo"
        />
      </div>
    </div>
  </BasicModal>

  <CustomerModal @register="registerCustomer"></CustomerModal>
  <BusinessCustomerModal @register="registerBusinessCustomer" @success="init"></BusinessCustomerModal>
  <AccountModal @register="registerAccount" @success="handleAccountSuccess"></AccountModal>
  <BusinessPrint @register="registerBusinessPrint" @success="init"></BusinessPrint>
  <AccountExcel @register="registerAccountExcel" @success="init"></AccountExcel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, onMounted, reactive, nextTick } from "vue";
import { Input, Popover, Pagination, Empty } from 'ant-design-vue';
import { BasicModal, useModal, useModalInner } from "/@/components/Modal";
import {
  businessById,
  businessStat,
  accountSave,
  accountRecall,
  accountDelete,
  accountStat,
  coopSelect,
  businessCustomerStatus, businessCustomerDel, businessUpdate
} from "./business.api";
import { loadBusinessAccount} from "/@//views/full/account/types/accountflow.api";
import { useMessage } from "/@/hooks/web/useMessage";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import AButton from "/@/components/Button/src/BasicButton.vue";
//import { Cascader } from 'ant-design-vue';
//import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";

import CustomerModal from "/@/views/full/customer/components/Customer.vue";
import BusinessCustomerModal from "./BusinessCustomerModal.vue";
import AccountModal from "./AccountModal.vue";
import BusinessPrint from "./BusinessPrint.vue";
import AccountExcel from "./AccountExcel.vue";
import { jsonPrint } from "/@/views/full/business/business.print";

let loading     = ref(false);
let $businessId = ref('');
let oAccountId  = ref('');
let ddztBoolean = ref<boolean>(false);
let isReload    = ref<boolean>(false);
let buttonAll   = ref<boolean>(false);
let business = reactive<any>({});
let customer = reactive<any>({});
let account  = reactive<any>({});
let schedule = reactive<any>({});
const { createMessage: $message } = useMessage();

// 声明Emits
const emit = defineEmits(["success", "register"]);

//TODO ------界面初始化---加载数据 -> 根据数据初始表单-------------
//表单赋值
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  //重置表单
  //await resetFields();
  //setModalProps({confirmLoading: false});
  //表单赋值
  buttonAll.value  = data.buttonAll
  oAccountId.value = data.oAccountId
  init(data.id);
});

function init(id) {
  if (!id && !$businessId.value) {
    alert("businessOrder, 订单编号不能为空!");
    return;
  }
  if (id) {
    $businessId.value = id;
  }
  handleSuccess();
}

const businessOption = reactive<any>({
  modButton: false, //修改订单
  dooButton: false, //确认订单
  canButton: true,  //取消订单
  accbutton: true,
  travelLineDisabled: true,
  cfsjDisabled: true,
  ywlxDisabled: true,
  ddlxDisabled: true
});

//订单界面所有信息
async function orderTable() {
  Object.keys(schedule).forEach( key => {
    delete schedule[key]
  })
  clearData();
  loading.value = true;
  var params = { businessId: $businessId.value };//查询条件
  await businessById(params).then((res) => {
    try {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      }
      ddztBoolean.value = false;
      let result = res.result;
      //1、业务数据 - 初始化
      Object.assign(business, result.business);
      Object.assign(customer, result.customer);
      Object.assign(account, result.account);
      Object.assign(schedule, result.schedule);
      //console.info("business@@",business)
      //临时记录出发时间
      business.sdate = business.cfsj

      //2、收支表单 - 构建组团社下拉框数据
      accountOption.customerNameSelect = [];
      if (customer && customer.optionList) {
        var optionList = customer.optionList
        for (var i = 0; optionList.length > i; i++) {
          accountOption.customerNameSelect.push({
            label: optionList[i].rowIndex + ") "+ optionList[i].customerDwmc,
            value: optionList[i].id,
            rowIndex: optionList[i].rowIndex,
          })
        }
      }

      //3、收支表单 - 构建支出项目下拉框数据
      //coopSelectLoadData(false)
    } catch (e) {
      alert(e);
      return false;
    }
  }).finally(() => {
    loading.value = false;
  });
}

//TODO ------顶部按钮----------------
//确认订单
function handleBusinessDdzt(ddzt) {
  //应收款
  var order_ygs = business.ygs;
  //应付款
  var order_ygf = business.ygf;
  //已收款
  var order_yjs = business.yjs;
  //已付款
  var order_yjf = business.yjf;
  var sumzero = (parseFloat(order_ygs) + parseFloat(order_ygf) + parseFloat(order_yjs) + parseFloat(order_yjf));
  //采购单位还有未收款
  var customer_wsk_boolean = parseFloat(customer.hjwskAbs.replace(",", ""));
  if (sumzero > 0 && ddzt == 1) {
    let lists = account.optionList
    if (lists.length > 0) {
      for (var i = 0; i < lists.length; i++) {
        if (lists[i].stat != '3' && lists[i].sffs != '3') {
          ddztBoolean.value = true;
        }
      }
    } else {
      ddztBoolean.value = false
    }

    if (ddztBoolean.value) {
      $message.warning('收付项目为空，或有未审核的收付款，请联系财务尽快审核后再确认订单！');
      return false
    }
    if (customer_wsk_boolean != 0) {
      $message.warning('该订单还有未收款：‘' + customer_wsk_boolean + '’，请尽快催款完成订单！');
      return false
    }
  }

  let params = { id: business.id, ddzt: ddzt };
  businessStat(params).then((res) => {
    if (res.success) {
      handleSuccess()
      //this.setIsReload(true) //变量在 curdtools.js 里
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  });
}

function handleBusinessUpdate() {
  if (business.ddlx == "") {
    $message.warn("线路分类不可为空请选择");
    return;
  }
  let param = {
    id : business.id,
    orderId : business.orderId,
    travelLine : business.travelLine,
    ddlx : business.ddlx,
    ywlx : business.ywlx,
    cfsj : business.cfsj,
    bz : business.bz,
    sdate : business.sdate,
    userId : business.userId,
  }
  loading.value = true;
  businessUpdate(param).then((res) => {
    if (res.success == true) {
      $message.success(res.message);
      handleSuccess();
      isReload.value = true; //变量在 curdtools.js 里
    } else {
      $message.error(res.message);
    }
  }).finally(() => {
    loading.value = false;
  });
}

//按数据状态，启用禁用界面所有表单属性
function refreshOrderButton() {
  var ddzt = business.ddzt;
  var isCurrentUser = business.isCurrentUser;
  //界面按键默认为禁用：当前订单状态为未确认，并且是本人创建的订单，才有修改的权限
  if (ddzt == "0" && isCurrentUser == "true") {
    //订单按钮
    businessOption.modButton = false;
    businessOption.dooButton = false;
    businessOption.canButton = true;
    //$("#accbutton").attr("disabled", false); //收付款保存
    businessOption.travelLineDisabled = false;
    businessOption.cfsjDisabled = false;
    businessOption.ywlxDisabled = false;
    businessOption.ddlxDisabled = false;

    //供应商 - 复选框，按钮
    businessCustomerOption.disabled = false;
    businessCustomerOption.btnAddDisabled = false;
    businessCustomerOption.btnLxrDisabled = false;
    businessCustomerOption.btnCanDisabled = false;
    businessCustomerOption.btnVerDisabled = false;
    //$("#accbutton, #clrbutton").removeClass("pub_but_disable").addClass("pub_but");

    //收支项目 - 按钮，复选框
    accountOption.disabled = false;
    accountOption.btnAddDisabled = false;
    accountOption.btnEdtDisabled = false;
    accountOption.btnDelDisabled = false;
    accountOption.btnStaDisabled = false;
    accountOption.btnRecDisabled = false;
  } else {
    //订单按钮
    businessOption.modButton = true;
    businessOption.dooButton = true;
    businessOption.canButton = false;
    //$("#accbutton").attr("disabled", false); //收付款保存
    businessOption.travelLineDisabled = true;
    businessOption.cfsjDisabled = true;
    businessOption.ywlxDisabled = true;
    businessOption.ddlxDisabled = true;

    //供应商按钮
    businessCustomerOption.disabled = true;
    businessCustomerOption.btnAddDisabled = true;
    businessCustomerOption.btnLxrDisabled = true;
    //$("#accbutton, #clrbutton").removeClass("pub_but_disable").addClass("pub_but");

    //$(".list #acctable input[name='ids']:enabled").attr("disabled", false);
    //收支项目 - 按钮、复选框
    accountOption.disabled = true;
    accountOption.btnAddDisabled = true;
    accountOption.btnEdtDisabled = true;
    accountOption.btnDelDisabled = true;
    accountOption.btnStaDisabled = true;
    accountOption.btnRecDisabled = true;
  }

  businessCustomerOption.btnEdtDisabled = true;
  businessCustomerOption.btnDelDisabled = true;
  businessCustomerOption.btnCanDisabled = true;
  businessCustomerOption.btnVerDisabled = true;


  accountOption.btnEdtDisabled = true;
  accountOption.btnDelDisabled = true;
  accountOption.btnStaDisabled = true;
  accountOption.btnRecDisabled = true;

  if (isCurrentUser == false) {
    businessOption.canButton = false;
  }

  //收支明细全选，默认为不勾选
  businessCustomerOption.checked = false;
  businessCustomerOption.nid = []
  businessCustomerOption.osn = []

  //收支明细全选，默认为不勾选
  accountOption.checked = false;
  accountOption.nid = []

  //查询内容
  accountOption.queryParams = "";
  accountOption.pageNo = 1;
  accountOption.pageSize = 100; 
}

/**
 * 操作成功
 */
function handleSuccess() {
  orderTable().then(() => {
    refreshOrderButton()
    doclear()
  });
}

//TODO ------采购单位----------------------------------------------------------
/**
 * 采购单位 操作属性
 * 作者：qdl
 * 日期：2022-06-28
 */
const businessCustomerOption = reactive<any>({
  btnAddDisabled: false,
  btnEdtDisabled: true,
  btnDelDisabled: true,
  btnLxrDisabled: true,
  btnCanDisabled: true, //已取消
  btnVerDisabled: true, //已审核
  checked: false,
  nid: [],
  osn: [],
});

/**
 * 采购单位 列表 全选
 * 作者：qdl
 * 日期：2022-06-28
 */
function bucAllCheck() {
  var me = businessCustomerOption;
  me.checked = !me.checked;
  if (me.checked == false) {
    me.nid = [];//清空数据
    me.osn = [];
    me.btnAddDisabled = false;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = true;
  } else {
    customer.optionList.forEach((s) => {
      // 防止重复数据
      if (me.nid.indexOf(s.id) == -1) {
        me.nid.push(s.id);
      }
      if (s.orderSn && me.osn.indexOf(s.orderSn) == -1) {
        me.osn.push(s.orderSn);
      }
    });
    console.info("@@@@00", me.osn)
    me.btnAddDisabled = true;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = false;
  }
}

/**
 * 采购单位 列表 单选
 * 作者：qdl
 * 日期：2022-06-28
 */
function bucOneCheck(index) {
  var list  = customer.optionList;
  var $id   = list[index].id;
  var $stat = list[index].status;
  var $osn  = list[index].orderSn;

  //勾选赋值
  var me  = businessCustomerOption;
  var idx = me.nid.indexOf($id);
  if (idx !== -1) {
    me.nid.splice(idx, 1);
  } else {
    me.nid.push($id);
  }

  // 2024-07-18 qindl 
  var sdx = me.osn.indexOf($osn);
  if (sdx !== -1) {
    me.osn.splice(sdx, 1);
  } else {
    me.osn.push($osn);
  }
  //console.info("@@@@00", me.osn)
  //订单未确认
  if (business.ddzt == 1) {
    me.btnAddDisabled = false;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = true;
    return false
  }

  //没有勾选
  if (me.nid.length == 0) {
    me.btnAddDisabled = false;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = true;
    me.checked = false;
    return false
  }

  //勾选的数量等于列表的数量
  if (me.nid.length == customer.optionList.length) {
    me.checked = true;
  }

  //勾选一个时才可编辑
  if (me.nid.length == 1) {
    me.btnEdtDisabled = false;
  } else {
    me.btnEdtDisabled = true;
  }
  me.btnDelDisabled = false;
  me.btnAddDisabled = true;

  if ($stat == 0) {
    me.btnCanDisabled = false;
    me.btnVerDisabled = false;
  } else if ( $stat == 1 ) {
    me.btnCanDisabled = false;
    me.btnVerDisabled = true;
  } else if ( $stat == 9 ) {
    me.btnCanDisabled = true;
    me.btnVerDisabled = false;
  }
}

/**
 * 采购单位 注册弹出编辑窗口
 * 作者：qdl
 * 日期：2022-06-28
 */
const [registerBusinessCustomer, { openModal: businessCustomerModal }] = useModal();

/**
 * 采购单位 打开添加编辑窗口
 * 作者：qdl
 * 日期：2022-06-28
 */
function handleBusinessCustomerAdd() {
  let isUpdate = false;
  let params   = { id: null, businessId: $businessId.value, orderId: business.orderId };
  let sche = {}

  if (businessCustomerOption.nid.length == 0) {
    isUpdate = false
  } else if (businessCustomerOption.nid.length == 1) {
    params.id = businessCustomerOption.nid[0];
    isUpdate = true
  } else {
    $message.warning("一次编辑操作只能选择一条记录！");
    return;
  }

  if (!isUpdate && schedule.id) {
    sche = {
      scheduleId: schedule.id,
      crj: schedule.price || 0,
      etj: schedule.priceChild || 0,
      priceVip: schedule.priceVip || 0,
      priceRoom: schedule.priceRoom || 0,
      sumPersonNo: customer.sumPersonNo || 0,
      seat: schedule.seat || 0,
      resi: Number(schedule.seat || 0) - Number(customer.sumPersonNo || 0),
    }
    Object.assign(params, sche);
  }

  //console.info(params, isUpdate)
  businessCustomerModal(true, { params, isUpdate });
}

/**
 * 采购单位 删除
 * 作者：qdl
 * 日期：2022-06-28
 */
 function handleBusinessCustomerDel() {
  let me = businessCustomerOption
  if (me.nid.length <= 0) {
    $message.warning('请选择一条记录！')
    return
  } else {
    let params = { ids: me.nid.join(','), orderSn: me.osn.join(','), businessId: $businessId.value };
    businessCustomerDel(params, handleSuccess);
  }
}

/**
 * 采购单位 审核
 * 作者：qdl
 * 日期：2022-06-13
 */
 function handleBusinessCustomerVer() {
  let me = businessCustomerOption
  if (me.nid.length <= 0) {
    $message.warning('请选择一条记录！')
    return
  }
  let params = { ids: me.nid.join(','), businessId: $businessId.value, status: '1' };
  businessCustomerStatus(params).then((res) => {
    if (res.success) {
      handleSuccess()
      //this.setIsReload(true) //变量在 curdtools.js 里
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  })

}

/**
 * 采购单位 取消
 * 作者：qdl
 * 日期：2024-06-13
 */
 function handleBusinessCustomerCan() {
  let me = businessCustomerOption
  if (me.nid.length <= 0) {
    $message.warning('请选择一条记录！')
    return
  }
  let params = { ids: me.nid.join(','), businessId: $businessId.value, status: '9' };
  businessCustomerStatus(params).then((res) => {
    if (res.success) {
      handleSuccess()
      //this.setIsReload(true) //变量在 curdtools.js 里
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  })
}

/**
 * 采购单位 - 例表 - 状态样式
 * 作者：qdl 
 * 日期：2024-06-12
 * 0 未审核，1 已审核，9 已取消
 */
function bccStatClass(stat) {
  var statClass = "";
  if (stat == "2") {
    statClass = "text-red-500"; //已审核
  } else if (stat == "9") {
    statClass = "text-green-500";
  } else {
    statClass = "";
  }
  return statClass;
}


//TODO ------供应商----------------------------------------------------------
/**
 * 供应商 注册
 * 作者：qdl
 * 日期：2022-06-28
 */
const [registerCustomer, { openModal: customerModal }] = useModal();

/**
 * 供应商 添加
 * 作者：qdl
 * 日期：2022-06-28
 */
function handleCustomerAdd() {
  customerModal(true, {isUpdate : false});
}

//TODO ------收支项目---------------------------------------------------------------------
let accForm = reactive<any>({});
const accountOption = reactive<any>({
  showBankdjm: true, //显示银行账号
  checked: false,
  nid: [],
  disabled: false,
  customerNameSelect: [],
  cooperatorNameSelect: [],
  cooperatorPath:[],
  sfsjDisabled: false,
  queryParams: '',
  pageNo: 1,
  pageSize: 100
});

// 全选
function accAllCheck() {
  let me = accountOption;
  me.checked = !me.checked;
  if (me.checked == true && business.ddzt == 0) {
    account.optionList.forEach((s) => {
      if (me.nid.indexOf(s.id) == -1 && s.stat !== '3') {
        me.nid.push(s.id);
      }
    });
    me.btnAddDisabled = true;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = false;
    me.btnStaDisabled = false;
    me.btnRecDisabled = false; //招回
  } else {
    me.nid = [];//清空数据
    me.btnAddDisabled = false;
    me.btnEdtDisabled = true;
    me.btnDelDisabled = true;
    me.btnStaDisabled = true;
    me.btnRecDisabled = true; //招回
  }
}

//收支项目 - 勾选 - 操作按钮属性
function accOneCheck(index) {
  var list = account.optionList;
  //account.stat: 0：新增；1：提交；2：经理；3：财务；8：招回；9：回退
  //account.sffs: 1:;2:;3:挂账
  var $stat = list[index].stat;
  var $sffs = list[index].sffs;
  var $id   = list[index].id;

  //勾选赋值
  var me  = accountOption;
  var idx = me.nid.indexOf($id);
  if (idx !== -1) {
    me.nid.splice(idx, 1);
  } else {
    me.nid.push($id);
  }

  //勾选按数据状态设置操作按钮
  if (me.nid.length > 0 && business.ddzt == 0) {
    if (me.nid.length == list.length) {
      me.checked = true; //全选
    }
    //添加
    me.btnAddDisabled = true;
    //编辑
    if (($stat == 0 || $stat == 8 || $stat == 9) && me.nid.length == 1) {
      me.btnEdtDisabled = false; //.removeClass('disableCss')
    } else {
      me.btnEdtDisabled = true; //.addClass('disableCss')
    }
    //提交
    //if(($stat == 0 || $stat == 8 || $stat == 9) && $sffs != 3){
    if ($stat == 0 || $stat == 8 || $stat == 9) {
      me.btnStaDisabled = false; //.removeClass('disableCss')
    } else {
      me.btnStaDisabled = true; //.addClass('disableCss')
    }
    //删除
    if (($stat == 0 || $stat == 8 || $stat == 9)) {
      me.btnDelDisabled = false; //.removeClass('disableCss')
    } else {
      me.btnDelDisabled = true; //.addClass('disableCss')
    }
    //招回
    //if($stat == 1 && $sffs != 2 && $sffs != 3){
    if ($stat == 1) {
      me.btnRecDisabled = false; //.removeClass('disableCss')
    } else {
      me.btnRecDisabled = true; //.addClass('disableCss')
    }
    //挂账
    if ($sffs == 3) {
      //$accIdsCheck.attr("checked", false);
      //$accIdsCheck.attr("disabled", true);
      //$(this).attr("disabled", false);
      //$(this).attr("checked", true);
    } else {
      //$accIdsCheck.attr('disabled', false)
    }
    //-----------------------------------------
  } else {
    me.btnAddDisabled = false;
    me.btnDelDisabled = true;
    me.btnEdtDisabled = true;
    me.btnStaDisabled = true;
    me.btnRecDisabled = true; //回退

    //$accIdsCheck.attr('disabled', false) //勾选全禁
  }
}

//收支项目 - 例表 - 状态样式
function accStatClass(stat) {
  var color = "";
  if (stat == "3") {
    color = "text-red-500"; //已审核
  } else if (stat == "9") {
    color = "text-green-500";
  } else {
    color = "";
  }
  return color;
}

//收支项目 - 例表 - 状态样式
function accSffsClass(sffs) {
  var color = "";
  if (sffs == "1") {
    color = "text-red-500"; //已审核
  } else if (sffs == "3") {
    color = "text-blue-500";
  } else if (sffs == "4") {
    color = "text-purple-500";
  } else if (sffs == "5") {
    color = "text-orange-500";
  } else {
    color = "";
  }
  return color;
}

function coopSelectChange(value) {
  //this.path.account.coopSelectValue = value;
}

async function coopSelectLoadData(selectedOptions) {
  var params = {}
  var value = ''
  var targetOption:any = {}
  if (selectedOptions) {
    targetOption = selectedOptions[selectedOptions.length - 1]
    targetOption.loading = true
    value = targetOption.value
    if (value) {
      params = { pid: value }
    }
  }
  await coopSelect().then((res) => {
    try {
      if (value) {
        targetOption.loading = false
        targetOption.children = res
        accountOption.cooperatorNameSelect = [...accountOption.cooperatorNameSelect]
      } else {
        accountOption.cooperatorNameSelect = res
      }
    } catch (e) {
      alert('loadTree' + e)
      return false
    }
  }).finally()
}

/**
 * 收支项目 注册弹出编辑窗口
 * 作者：qdl
 * 日期：2022-07-04
 */
const [registerAccount, { openModal: accountModal }] = useModal();

//收支项目 - 添加
function handleAccountAdd() {
  let record = { 
    id: null, 
    businessId: $businessId.value, 
    orderId: business.orderId, 
    ddlx: business.ddlx 
  };
  let customerNameSelect = accountOption.customerNameSelect
  let isUpdate = false
  if (accountOption.nid.length == 0) {
    record.id = null;
    isUpdate = false;
  } else if (accountOption.nid.length == 1) {
    record.id = accountOption.nid[0];
    isUpdate = true;
    if (!record.id) {
      $message.error("操作失败：编辑收支项目编号不能空！");
      return
    }
  } else if (accountOption.nid.length > 1) {
    $message.warning("一次编辑操作只能选择一条记录！");
    return;
  }
  //检查订单编号
  if (!$businessId.value) {
    $message.warning("订单编号不能为空！");
    return;
  }

  accountModal(true, {record, isUpdate, customerNameSelect});
}

function handleAccountSuccess(id) {
  oAccountId.value = id;
  handleSuccess();
}

//双击行可直接编辑数据
function handleAccountEdit(id, stat, statZw) {
  if (!stat) {
    $message.warning("操作失败：数据状态为空！");
    return;
  }
  if ('1,2,3'.indexOf(stat) >= 0) {
    $message.warning("操作失败：数据当前，状态=" + statZw + "不可编辑！");
    return;
  }
  let record = {
    id: id,
    businessId: $businessId.value,
    orderId: business.orderId
  };
  let customerNameSelect = accountOption.customerNameSelect
  let isUpdate = true
  accountModal(true, {record, isUpdate, customerNameSelect});
}

//收支项目 - 删除
function handleAccountDel() {
  let me = accountOption
  if (me.nid.length <= 0) {
    $message.warning('请选择删除的记录！')
    return
  }
  let params = { ids: me.nid.join(','), businessId: unref($businessId) };
  accountDelete(params, handleSuccess)
}

//收支项目 - 提交
function handleAccountStat() {
  let me = accountOption
  if (me.nid.length <= 0) {
    $message.warning('请选择删除的记录！')
    return
  }
  let params = { ids: me.nid.join(',') };
  accountStat(params).then((res) => {
    if (res.success) {
      handleSuccess()
      //this.setIsReload(true) //变量在 curdtools.js 里
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  })
}

//收支项目 - 招回
async function handleAccountRecall() {
  await accountRecall({ ids: accountOption.nid }).then((res) => {
    if (res.success) {
      handleSuccess()
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  });
}

//收支信息保存
function handleAccountSave() {
  var flag = true
  var id   = accForm.id || ''
  var sflx = accForm.sflx || ''
  var fklx = accForm.fklx || ''
  var sffs = accForm.sffs || ''
  var je   = accForm.skje || ''
  var bz   = accForm.bz || ''
  var sfsj    = accForm.sfsj || ''
  var bank_id = accForm.bankId || ''
  var buc_id  = accForm.bcId || ''
  var coop_id = ''//$('select.cooperator_id').val()

  if (accForm.sflx == '') {
    flag = false
    $message.warning('请选择收支类型')
    return false
  }
  if (sflx != '' && sffs == '') {
    flag = false
    $message.warning('请选择收支方式')
    return false
  }
  if (sflx != '' && sflx != '' && je == '') {
    flag = false
    $message.warning('金额不能为空')
    return false
  } else if (sflx != '' && sffs == '' && je != '' && parseFloat(je) <= 0) {
    flag = false
    $message.warning('输入金额应大于0')
    return false
  }
  //收支类型: 1收入，2支出； 收支方式：1转账，3付现，2挂账
  if (sflx == '1' && sffs == '1') {
    if (buc_id == '') {
      flag = false
      //document.f.customerDwmcSelect.onfocus
      $message.warning('请选择订购单位！')
      return false
    }
    if (bank_id == '') {
      flag = false
      //document.f.account_bank_id.onfocus
      $message.warning('请选择转帐银行！')
      return false
    }
    if (sfsj == '') {
      flag = false
      //document.f.account_sfsj.onfocus
      $message.warning('收款时间不能为空！')
      return false
    }
  } else {
    if (coop_id == null || coop_id == '') {
      flag = false
      //document.f.cooperator_dwmc.onfocus;
      $message.warning('付款单位不能为空请选择！')
      return false
    }
  }

  //$('#accbutton').attr('disabled', true) //收付款保存
  if (!flag) {
    return false
  }

  if (sflx == 1) {
    accForm.skje = je
    accForm.fkje = 0
    accForm.fklx = ''
    accForm.bcId = buc_id
    accForm.coopId = ''
  } else if (sflx == 2) {
    accForm.fkje = je
    accForm.skje = 0
    accForm.fklx = fklx
    accForm.bcId = ''
    accForm.coopId = coop_id
  }
  accForm.businessId = business.id;

  accountSave(accForm).then((res) => {
    if (res.success) {
      handleSuccess();
    }
    $message.warning(res.message)
  }).finally(() => {
    //that.confirmLoading = false;
  })
}

//收支方式，值变化时触发
function changeAccountSffs() {
  //console.info("sffssffs@@",accForm.sffs )
  if (accForm.sffs == 2) {
    return false;
  }
  if (accForm.sffs == 3) {
    accForm.bankId = "";
    accForm.sfsj = "";
    accountOption.bankDisabled = true;
    accountOption.sfsjDisabled = true;
  } else {
    accountOption.bankDisabled = false;
    accountOption.sfsjDisabled = false;
  }
}

function doclear() {
  accForm.id = null
  accForm.sflx = '1'
  accForm.bcId = ''
  accForm.skje = ''
  accForm.sffs = '1'
  accForm.bankId = ''
  accForm.sfsj = ''
  accForm.bz = ''
  accountOption.bankDisabled = false
  accountOption.sfsjDisabled = false
}

// 赋值数据前 - 清空对象
function clearData() {
  loading.value = true;

  //业务信息
  Object.keys(business).forEach( key => {
    delete business[key]
  })

  //业务收支明细
  Object.keys(customer).forEach( key => {
    delete customer[key]
  })

  //业务收支明细
  Object.keys(account).forEach( key => {
    delete account[key]
  })

}

const [registerBusinessPrint, { openModal: businessPrintModal }] = useModal();
function handleBusinessPrint() {
  jsonPrint(business, customer, account);
  //businessPrintModal(true, {businessId: business.id})
}

function handleScroll() {
  let scrollTop = document.getElementsByClassName('orderTable')[0].scrollTop;
  //console.log('【滚动距离】', scrollTop, document.body.scrollTop);
  //let ch = document.getElementsByClassName('orderTable')[0].clientHeight;
  //console.log('【可视区域】', ch);
  //let sh = document.getElementsByClassName('strategy-box')[0].scrollHeight;
  //console.log('【滚动条高度】', sh);
  /*scrollTop + ch = sh*/
}

/**
 * 收支项目 注册弹出编辑窗口
 * 作者：qdl
 * 日期：2022-07-04
 */
const [registerAccountExcel, { openModal: accountExcel }] = useModal();

//产品排期价格余位
const scheduleInfo = computed(() => {
  if (!schedule || schedule.seat == 0) {
    return '现询'
  } else {
    return (schedule.seat - customer.sumPersonNo) + "/" + schedule.seat
  }
});


function handleAccountExcel() {
  accountExcel(true, {businessId: business.id, orderId: business.orderId, travelLine: business.travelLine})
}

// 收支项目 - 查询
function onAccountSearch() {
  accountOption.pageNo = 1;
  accountOption.pageSize = 100;
  onAccountPageNo();
}

// 收支项目 - 分页
function onAccountPageNo() {
  console.info(accountOption.pageNo)
  var params  = { 
    "businessId": $businessId.value, 
    "bmmc": accountOption.queryParams,
    "pageNo": accountOption.pageNo,
    "pageSize": accountOption.pageSize
  };
  //清空对象
  Object.keys(account).forEach( key => {
    delete account[key]
  })
  loadBusinessAccount(params).then((res) => {
    // console.info(res.result)
    Object.assign(account, res.result);
  });
}

onMounted(async () => {
  //window.addEventListener('scroll', handleScroll, true)
});

</script>

<style lang="less" scoped>
@import "./order.css";
// newCode：新代码改为
body,html {
  width: 100%;
  min-height: 100vh;
}
.orderTable .ant-form-item {
  margin-bottom: 0px;
}

.jeecg-modal-wrapper {
  overflow: hidden;
}

.theadSticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
  z-index: 10;

  padding:6px 4px;
  background:#fff;
  border: 1px solid #d6dde7;
  height: 42px;
  line-height: 30px;
  margin-bottom: -1px;
  font-size: 16px;
}

.serial-number {
  display: inline-block;
  min-width: 14px;
  height: 14px;
  line-height: 14px;
  text-align: center;
  background-color: #888;
  color: white;
  border-radius: 50%;
  font-size: 10px;
  margin: 3px;
  vertical-align: middle; /* 添加垂直居中对齐 */
  /* 调整外边距，确保与后续文字对齐 */
  margin-right: 4px;
  margin-top: 0px;
}

.serial-dwmc {

}
</style>
